import simplejson
import sys
import urllib2 as u2

import re

import logging
import pprint
import unittest

class UserTimeline:
    TWITTER_API = 'http://twitter.com/statuses/user_timeline/'
    
    def __init__(self, username, since_id = None):
        self.username = username
        self.since_id = since_id
    
    def getLastUpdates(self):
        urlparams = '%s.json?count=25' % self.username
        
        if None != self.since_id:
            urlparams = urlparams + ('&since_id=%s' % self.since_id)
        
        
        logging.debug("Will be requesting : %s%s" % (self.TWITTER_API, urlparams))
        
        jsonData = u2.urlopen('%s%s' %  (self.TWITTER_API, urlparams)).read().decode('utf-8')
        result = simplejson.loads(jsonData)
        
        
        return result
    
    def getOldUpdates(self, callback):
        urlparams = '%s.json?count=200' % self.username
        urlparams = urlparams + '&since_id=1'
        
        for page in range(1, 16 ):
            query = urlparams + '&page=1'
            logging.debug("Will be requesting : %s%s" % (self.TWITTER_API, query))
            jsonData = u2.urlopen('%s%s' %  (self.TWITTER_API, urlparams)).read().decode('utf-8')
            if len(jsonData) < 5:
                break
            
            result = simplejson.loads(jsonData)
            callback(result)
            page = page + 1
        
        logging.debug("All done")
        

class UserTimelineTest(unittest.TestCase):
    def setUp(self):
        logging.basicConfig(level=logging.DEBUG)
    
    def testSimple(self):
        ut = UserTimeline(username='sigizmund')
        results = ut.getLastUpdates()
        self.assertEquals(25, len(results))


if __name__ == '__main__':
    unittest.main()
     